package com.github.caijh.mall.utils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

import com.github.caijh.framework.core.exception.BizException;
import com.github.caijh.mall.common.MessageConstants;
import com.github.caijh.mall.upload.vo.FileResultVo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
public class LocalUploadStrategy implements UploadStrategy {

    @Override
    public FileResultVo upload(MultipartFile multipartFile, UploadSpecs fileSpecs) {
        String newFileName = fileSpecs.getNewFileName();
        String destPath = FilenameUtils.separatorsToSystem(fileSpecs.getRootPath() + fileSpecs.getWebPath()) + newFileName;
        try {
            File file = createFile(destPath);
            multipartFile.transferTo(file);
        } catch (IOException e) {
            throw BizException.of(MessageConstants.UPLOAD_EXCEPTION_FILE_FAIL);
        }

        FileResultVo fileResultVo = new FileResultVo();
        fileResultVo.setFileName(newFileName);
        fileResultVo.setType(multipartFile.getContentType());
        fileResultVo.setExtName(fileSpecs.getExtName());
        fileResultVo.setServerPath(destPath);
        fileResultVo.setUrl(fileSpecs.getWebPath() + newFileName);
        fileResultVo.setFileSize(multipartFile.getSize());
        return fileResultVo;
    }

    private File createFile(String filePath) throws IOException {
        String fileDir = FilenameUtils.getFullPath(filePath);
        File file;
        try {
            file = new File(fileDir);
            if (!file.mkdirs()) {
                throw new IOException("创建目录失败");
            }
            file = new File(filePath);
            Files.createFile(file.toPath());
        } catch (IOException e) {
            throw BizException.of(MessageConstants.UPLOAD_EXCEPTION_FILE_FAIL);
        }
        return file;
    }

}
